<template>
  <div class="scale-box">
    <div
      class="scale-box-inner"
      :style="boxStyle"
    >
      <div
        class="scale-box-inner__container"
        :class="containerClassName"
        :style="innerContainerStyle"
      >
        <slot />
      </div>
    </div>
    <div
      class="scale-box-chink"
      :style="{paddingTop:ratioPercent? ratioPercent + '%':null}"
    ></div>
  </div>
</template>

<script>
export default {
  name: 'ScaleBox',
  props: {
    ratio: {
      type: Number,
      default: 1
    },
    radius: [Number, String],
    containerClass: String,
    bgColor: String,
    bgImage: String,
    containerStyle: Object,
    flex: Boolean
  },
  data () {
    return {
      borderRadius: 0
    }
  },
  computed: {
    containerClassName () {
      let className = []
      if (this.flex) {
        className.push('scale-box-inner__flex')
      }
      if (this.containerClass) {
        className.push(this.containerClass)
      }
      return className
    },
    ratioPercent () {
      let ratio = Math.abs(this.ratio)
      if (ratio === 1 || ratio === 0) {
        return 0
      }
      return 100 / ratio
    },
    innerContainerStyle () {
      let style = []
      if (this.bgColor) {
        style.push({
          background: this.bgColor
        })
      }
      if (this.bgImage) {
        style.push({
          backgroundImage: 'url(' + this.bgImage + ')'
        })
      }
      return style
    },
    boxStyle () {
      let radius = this.addUnit(this.radius)
      if (radius) {
        return 'border-radius:' + radius
      }
      return ''
    }
  },
  methods: {
    addUnit (value) {
      if (value) {
        return /^\d+(\.\d+)?$/.test(value) ? value + 'px' : value
      }
      return undefined
    }
  }
}
</script>

<style lang="less">
.scale-box {
  position: relative;
  width: 100%;
  overflow: hidden;
  &-chink {
    display: block;
    padding-top: 100%;
  }
  &-inner {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    &__flex {
      -moz-box-align: center;
      -moz-box-pack: justify;
      align-items: center;
      align-content: space-around;
      box-sizing: border-box;
      display: -webkit-box;
      display: -webkit-flex;
      display: flex;
      justify-content: center;
      flex-wrap: nowrap;
    }
    &__container {
      width: 100%;
      height: 100%;
      overflow: hidden;
      > .van-image {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
